package com.android.lovingpet.community.search;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.android.lovingpet.common.Back;
import com.android.lovingpet.common.FileModel;
import com.android.lovingpet.common.UserModel;
import com.android.lovingpet.bean.Account;

import java.util.ArrayList;
import java.util.List;

public class SearchModel {

    private static SearchModel instance;
    private SearchModel() {}
    public static SearchModel getInstance() {
        if (instance == null) {
            synchronized (SearchModel.class) {
                if (instance == null) {
                    instance = new SearchModel();
                }
            }
        }
        return instance;
    }

    public void search(String query, final int mode, final Back back) {
        Back backInfo = new Back() {
            @Override
            public void onFailure(String meg) {
                back.onFailure(meg);
            }

            @Override
            public void onSuccess(@Nullable Bundle bundle) {
                final List<Integer> ids = bundle.getIntegerArrayList("ids");
                if (ids == null) {
                    Bundle bundle2 = new Bundle();
                    bundle2.putParcelableArrayList("accounts", null);
                    bundle2.putInt("mode", mode);
                    back.onSuccess(bundle2);
                    return;
                }

                for (int id : ids) {
                    UserModel.getInstance().getInfo(id, new FileModel.FileBack() {
                        Account account;

                        @Override
                        public void loadSuccess(String url) {
                            account.setHead(url);
                            account.saveOrUpdate();
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("account", account);
                            back.onSuccess(bundle);
                        }

                        @Override
                        public void onFailure(String msg) {
                            back.onFailure(msg);
                        }

                        @Override
                        public void onSuccess(@Nullable Bundle bundle) {
                            account = bundle.getParcelable("account");
                        }
                    });
                }
            }
        };

        if (mode == 1) {
            UserModel.getInstance().getByPhone(query, backInfo);
        } else if (mode == 2) {
            UserModel.getInstance().getByEmail(query, backInfo);
        } else {
            UserModel.getInstance().getByName(query, backInfo);
        }
    }
}
